package com.kd.dao;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.kd.entity.Order;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.math.BigDecimal;

public interface OrderMapper extends BaseMapper<Order> {
    // 初始化每日序列（如果不存在）
    @Insert("INSERT INTO order_stats_daily (date_str, current_value, rev, active_count, sale_quantity) " +
            "VALUES (#{dateStr}, 0, 0, 0, 0) " +
            "ON DUPLICATE KEY UPDATE date_str = #{dateStr}")
    void insertDailyOrder(@Param("dateStr") String dateStr);


    // 原子性递增序列值
    @Update("UPDATE order_stats_daily SET current_value = current_value + 1 " +
            "WHERE date_str = #{dateStr}")
    void insertDailyStats(@Param("dateStr") String dateStr);

    // 获取当前序列值
    @Select("SELECT current_value FROM order_stats_daily WHERE date_str = #{dateStr}")
    int getCurrentSeq(@Param("dateStr") String dateStr);

//    // 全量更新当日统计（适合定时任务）
//    @Update("UPDATE order_stats_daily SET " +
//            "active_count = (SELECT COUNT(*) FROM orders WHERE DATE(orderdate) = #{date} AND status > 0), " +
//            "rev = (SELECT SUM(totalamount) FROM orders WHERE DATE(orderdate) = #{date} AND status > 0), " +
//            "sale_quantity = (SELECT SUM(quantity) FROM order_items oi " +
//            "JOIN orders o ON oi.order_id  = o.order_id  " +
//            "WHERE DATE(o.orderdate)  = #{date} AND o.status  > 0) " +
//            "WHERE date_str = #{dateStr}")
//    void updataDailyStats(@Param("date") String date, @Param("dateStr") String dateStr);

    // 合并后的增量更新方法（支持正负delta）
    @Update("UPDATE order_stats_daily SET " +
            "active_count = GREATEST(active_count + #{countDelta}, 0), " +
            "rev = GREATEST(rev + #{deltaAmount}, 0), " +
            "sale_quantity = GREATEST(sale_quantity + #{deltaQuantity}, 0) " +
            "WHERE date_str = #{date_str}")
    int updateDailyStats(@Param("date_str") String date_str,
                          @Param("countDelta") int countDelta,
                          @Param("deltaAmount") BigDecimal deltaAmount,
                          @Param("deltaQuantity") int deltaQuantity);

}
